/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pig4cloud.pig.common.security.component;

import cn.hutool.core.util.ReUtil;
import com.pig4cloud.pig.common.core.util.SpringContextHolder;
import com.pig4cloud.pig.common.security.annotation.Inner;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.RegEx;
import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author lengleng
 * @date 2020-03-11
 * <p>
 * 资源服务器对外直接暴露URL,如果设置contex-path 要特殊处理
 */
@Slf4j
@ConfigurationProperties(prefix = "security.oauth2.client")
public class PermitAllUrlProperties implements InitializingBean {

	private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");

	private static final String[] DEFAULT_IGNORE_URLS = new String[] { "/actuator/**", "/error", "/v3/api-docs" , "/v2/api-docs"
			,"/doc.html","/webjars/bycdao-ui/**","/swagger-resources/**"};

	@Resource
	RequestMappingHandlerMapping requestMappingHandlerMapping;

	@Getter
	@Setter
	private List<String> ignoreUrls = new ArrayList<>();

	@Override
	public void afterPropertiesSet() {
		ignoreUrls.addAll(Arrays.asList(DEFAULT_IGNORE_URLS));
		//RequestMappingHandlerMapping mapping = SpringContextHolder.getBean("requestMappingHandlerMapping");
		Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();

		map.keySet().forEach(info -> {
			HandlerMethod handlerMethod = map.get(info);
			//log.info("{}:{}:{}:{}",info,handlerMethod,info.getPathPatternsCondition(),info.getPatternsCondition());

			// 获取方法上边的注解 替代path variable 为 *
			Inner method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Inner.class);
			Optional.ofNullable(method)
					.ifPresent(inner -> {
						if(info.getPathPatternsCondition() != null){
							Objects.requireNonNull(info.getPathPatternsCondition())
									.getPatternValues()
									.forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, "*")));
						}else{
							Objects.requireNonNull(info.getPatternsCondition())
									.getPatterns()
									.forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, "*")));
						}

					});

			// 获取类上边的注解, 替代path variable 为 *
			Inner controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Inner.class);
			Optional.ofNullable(controller)
					.ifPresent(inner -> {
						if(info.getPathPatternsCondition() != null){
							Objects.requireNonNull(info.getPathPatternsCondition())
									.getPatternValues()
									.forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, "*")));
						}else{
							Objects.requireNonNull(info.getPatternsCondition())
									.getPatterns()
									.forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, "*")));
						}
					});
		});
		log.info("ignoreUrls::{}",ignoreUrls);
	}

}
